package com.ad.aidai.fragments.me.profile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.bean.OnActivityResultRequestCode;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.bind_school.BindSchoolFragment;
import com.ad.aidai.fragments.me.profile.update_name.UpNameFragment;
import com.ad.aidai.fragments.me.profile.update_pay_num.UpPayNumFragment;
import com.ad.aidai.fragments.me.profile.update_personal_note.UpPersonalNoteFragment;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalListDialog;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 个人资料页面
 * <p>
 * Created by pure on 2017/1/12.
 */

public class ProfileFragment extends BaseFragment implements ProfileContract.View {

    @BindView(R.id.rlv_profile)
    RecyclerView rlvProfileBase;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_profile_word)
    TextView tvProfileWord;

    private ProfileContract.Presenter mPresenter;

    private LoadingDialog loadingDialog;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_me_profile, container, false);
        mView.setClickable(true);//防止点击穿透，底层的fragment响应上层点击触摸事件
    }

    @Override
    protected void initView() {
        //创建默认的线性LayoutManager
        rlvProfileBase.setLayoutManager(new LinearLayoutManager(getActivity()));

        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        rlvProfileBase.setHasFixedSize(true);

        //设置分割线
        DividerDecoration itemDecoration = new DividerDecoration(Color.parseColor("#E6E6E6"), 3, 0, 0);
        itemDecoration.setDrawLastItem(true);
        rlvProfileBase.addItemDecoration(itemDecoration);
    }

    @Override
    protected void initData() {
        new ProfilePresenter(mContext, this).subscribe();
        rlvProfileBase.setAdapter(mPresenter.getAdapter());
        mPresenter.loadUserData();
    }

    @Override
    public void setPresenter(ProfileContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick({R.id.iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onActivityBackPressed();
                break;
        }
    }

    @Override
    public void modifyName(Bundle bundle) {
        UpNameFragment nameFragment = new UpNameFragment();
        nameFragment.setArguments(bundle);
        getFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                        .fragment_slide_left_exit)
                .add(android.R.id.content, nameFragment, "name")
                .addToBackStack("name")
                .commit();
    }

    @Override
    public void bindSchool() {
        getFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                        .fragment_slide_left_exit)
                .add(android.R.id.content, new BindSchoolFragment(), "bindSchool")
                .addToBackStack("bindSchool")
                .commit();
    }

    @Override
    public void modifyPayNum(Bundle bundle) {
        UpPayNumFragment payNumFragment = new UpPayNumFragment();
        payNumFragment.setArguments(bundle);
        getFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                        .fragment_slide_left_exit)
                .add(android.R.id.content, payNumFragment, "pay_num")
                .addToBackStack("pay_num")
                .commit();
    }

    @Override
    public void modifyPersonalNote(Bundle bundle) {
        UpPersonalNoteFragment personalNoteFragment = new UpPersonalNoteFragment();
        personalNoteFragment.setArguments(bundle);
        getFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                        .fragment_slide_left_exit)
                .add(android.R.id.content, personalNoteFragment, "personalNote")
                .addToBackStack("personalNote")
                .commit();
    }

    @Override
    public void selectSex() {
        ArrayList<DialogMenuItem> items = new ArrayList<>();
        items.add(new DialogMenuItem("男", R.mipmap.icon_male));
        items.add(new DialogMenuItem("女", R.mipmap.icon_female));
        final NormalListDialog dialog = new NormalListDialog(mContext, items);
        dialog.title("性别")
                .titleBgColor(ContextCompat.getColor(getContext(), R.color.colorTheme))
                .itemPressColor(Color.parseColor("#85D3EF"))
                .itemTextColor(Color.parseColor("#303030"))
                .itemTextSize(14)
                .cornerRadius(2)
                .widthScale(0.5f)
                .show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPresenter.userChangeSex(position);
                dialog.dismiss();
            }
        });
    }

    @Override
    public void chooseHeadImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setShowCamera(true);//显示拍照按钮
        imagePicker.setSelectLimit(1);//选中数量限制
        imagePicker.setCrop(true);
        imagePicker.setStyle(CropImageView.Style.CIRCLE);//裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);
        imagePicker.setSaveRectangle(true);
        imagePicker.setMultiMode(false);

        Intent intent = new Intent(mActivity, ImageGridActivity.class);
        startActivityForResult(intent, OnActivityResultRequestCode.CHOOSE_HEAD_IMAGE);
    }

    @Override
    public void copyWord(String content) {
        // 从API11开始android推荐使用android.content.ClipboardManager
        // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
        ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(content);
        toast("已复制到剪切板");
    }

    @Override
    protected void subscribeEvents() {
        //订阅事件
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof CommonEvent) {
                            CommonEvent event = (CommonEvent) o;
                            switch (event.getEvent()) {
                                case CommonEvent.USER_NAME:
                                    mPresenter.userModifyName();
                                    break;
                                case CommonEvent.SCHOOL_INFO_BIND:
                                    mPresenter.userBindSchool();
                                    break;
                                case CommonEvent.USER_PAY_NUM:
                                    mPresenter.userModifyPayNum();
                                    break;
                                case CommonEvent.USER_PERSONAL_NOTE:
                                    mPresenter.userModifyPersonalNote();
                                    break;
                                case CommonEvent.USER_HEAD_UPLOAD:
                                    mPresenter.uploadHead((String) event.getData());
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber()));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == OnActivityResultRequestCode.CHOOSE_HEAD_IMAGE) {
                List<ImageItem> images = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images.size() > 0) {
                    String path = images.get(0).path;
                    RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.USER_HEAD_UPLOAD, path));
                }
            }
        }
    }

    @Override
    public void showLoading(@NonNull String text) {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mActivity);
        loadingDialog.setLoadingText(text + "中...")
                .setFailedText(text + "失败")
                .setSuccessText(text + "成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void setTitle(String title) {
        tvTitle.setText(title);
        tvProfileWord.setText("资料");
    }

    @Override
    public boolean onActivityBackPressed() {
        getFragmentManager().popBackStack();
        return false;
    }
}
